﻿@page "/item/{itemId:int}"
@using System.Net
@inject eShop.HybridApp.Services.CatalogService CatalogService
@* @inject BasketState BasketState *@
@inject NavigationManager Nav
@inject IProductImageUrlProvider ProductImages

@if (item is not null)
{
    <PageTitle>@item.Name | AdventureWorks</PageTitle>
    <SectionContent SectionName="page-header-title">@item.Name</SectionContent>
    <SectionContent SectionName="page-header-subtitle">@item.CatalogBrand?.Brand</SectionContent>

    <div class="item-details">
        <img src="@ProductImages.GetProductImageUrl(item.Id)" />
        <div class="description">
            <p>@item.Description</p>
            <p>
                Brand: <strong>@item.CatalogBrand?.Brand</strong>
            </p>
            <form class="add-to-cart" >
                <span class="price">$@item.Price.ToString("0.00")</span>
            </form>

        @*     @if (numInCart > 0)
            {
                <p><strong>@numInCart</strong> in <a href="cart">shopping bag</a></p>
            } *@
        </div>
    </div>
}
else if (notFound)
{
    <SectionContent SectionName="page-header-title">Not found</SectionContent>
    <div class="item-details">
        <p>Sorry, we couldn't find any such product.</p>
    </div>
}

@code {
    private CatalogItem? item;
    // private int numInCart;
    // private bool isLoggedIn;
    private bool notFound;

    [Parameter]
    public int ItemId { get; set; }

    // [CascadingParameter]
    // public HttpContext? HttpContext { get; set; }

    protected override async Task OnInitializedAsync()
    {
        try
        {
            // isLoggedIn = HttpContext?.User.Identity?.IsAuthenticated == true;
            item = await CatalogService.GetCatalogItem(ItemId);
            // await UpdateNumInCartAsync();
        }
        catch (HttpRequestException ex) when (ex.StatusCode == HttpStatusCode.NotFound)
        {
            // HttpContext!.Response.StatusCode = 404;
            notFound = true;
        }
    }

    // private async Task AddToCartAsync()
    // {
    //     if (!isLoggedIn)
    //     {
    //         Nav.NavigateTo(Pages.User.LogIn.Url(Nav));
    //         return;
    //     }

    //     if (item is not null)
    //     {
    //         await BasketState.AddAsync(item);
    //         await UpdateNumInCartAsync();
    //     }
    // }

    // private async Task UpdateNumInCartAsync()
    // {
    //     var items = await BasketState.GetBasketItemsAsync();
    //     numInCart = items.FirstOrDefault(row => row.ProductId == ItemId)?.Quantity ?? 0;
    // }
}
